package xu.ye.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xu.ye.bean.ContactBean;
import xu.ye.bean.TypeBean;
import xu.ye.bean.TypeMiddleBean;
import xu.ye.uitl.BaseIntentUtil;
import xu.ye.uitl.MyDateUtil;
import xu.ye.view.adapter.TypeExpendAdapter;
import xu.ye.view.sms.MessageBoxList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

import com.agent.crm.bean.MyContact;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.util.DateUtils;
import com.agent.crm.view.R;
import com.pwp.activity.ScheduleView;

public class TypeContactActivity extends Activity{
    private ExpandableListView typeExpandView;
    private Button btn_addType;
    private List<List<MyContact>> typeContactData = new ArrayList<List<MyContact>>();
    private DatabaseManager manager = null;
    private TypeExpendAdapter adapter = null;
    private List<TypeBean> tbList = new ArrayList<TypeBean>();
    private List<MyContact> mcList = new ArrayList<MyContact>();
    private List<TypeMiddleBean> tmbList = new ArrayList<TypeMiddleBean>();
    
    private List<String> typeNameList = new ArrayList<String>();
    
    private String[] lianxiren1 = new String[] { "拨打电话", "发送短信", "查看详细", "添加关注", "添加任务", "移出联系人" };
    private String[] typeContactShow  = new String[] {"发送短信", "添加任务", "编辑分类组员", "编辑分类名称", "删除分类"};
    
    private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd");
    
    //新增请求码
    private static int ADD_REQUEST_CODE = 1;
    //编辑请求码
    private static int EDIT_REQUEST_CODE = 2;
    //群发消息请求码
    private static int MUTIL_SMS_REQUEST_CODE = 3;
    //编辑分类请求码
    private static int EDIT_TYPE_CONTACT_REQUEST_CODE = 4;
    //分类任务请求码
    public static final int TASK_ADD_REQUEST_CODE = 5;
    
    //年龄分类数量
    private int sysOldCount = 0;
    //默认分类数量
    private int sysConfigCount = 0;
    //年龄分类+默认分类=总数量
    private int sysCount = 0;
    
    
    
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.type_contact_page);
        typeExpandView = (ExpandableListView) findViewById(R.id.typeExpandViewId);
        if(null==manager){
            manager = new DatabaseManager(this);
        }
        btn_addType = (Button)findViewById(R.id.addTypeButtonId);
        btn_addType.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("edit", false);
                intent.setClass(TypeContactActivity.this, AddEditTypeActivity.class);
                startActivityForResult(intent, ADD_REQUEST_CODE);
            }
        });
        
        init();
        adapter = new TypeExpendAdapter(getApplicationContext(), typeNameList, typeContactData);
        typeExpandView.setAdapter(adapter);
        typeExpandView.setOnItemLongClickListener(typeItemLongListener);
        
        typeExpandView.setOnChildClickListener(new OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
                MyContact mc = (MyContact)adapter.getChild(groupPosition, childPosition);
                int isAttention = mc.getIsAttention();
                if(isAttention == 0){
                    lianxiren1[3] = "添加关注";
                }
                else{
                    lianxiren1[3] = "取消关注";
                }
                TypeBean tb = null;
                if(groupPosition + tbList.size() >= typeNameList.size()){
                    lianxiren1 = new String[] { "拨打电话", "发送短信", "查看详细", "添加关注", "添加定时任务", "删除"};
                    tb = tbList.get(groupPosition + tbList.size() - typeNameList.size());
                }
                else {
                    lianxiren1 = new String[] { "拨打电话", "发送短信", "查看详细", "添加关注", "添加定时任务"};
                }
                showContactDialog(lianxiren1, mc, tb, groupPosition, childPosition);
                return false;
            }
        });
        
        ((Button)findViewById(R.id.back)).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
    }
    
    OnItemLongClickListener typeItemLongListener = new OnItemLongClickListener(){

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view, int pos, long id) {
            int groupPosition = (Integer)view.getTag(R.id.xxx01); 
            int childPosition = (Integer)view.getTag(R.id.xxx02);  
            //长按父item
            if(childPosition == -1){
                TypeBean tb = null;
                int model = -1;
                if(groupPosition < sysOldCount){
                    typeContactShow  = new String[] {"群发短信", "添加定时任务"};
                    //属于动态计算分类中间表无数据
                    tb = null;
                    model = 0;
                    
                }
                else if(sysOldCount <= groupPosition && groupPosition < sysCount){
                    typeContactShow  = new String[] {"群发短信", "添加定时任务", "编辑组员"};
                    tb = tbList.get(groupPosition - sysOldCount);
                    model = 1;
                    
                }
                else if(groupPosition >= sysCount){
                    typeContactShow  = new String[] {"群发短信", "添加定时任务", "编辑组员", "编辑名称", "删除"};
                    tb = tbList.get(groupPosition - sysOldCount);
                    model = 2;
                }
                showTypeLongDialog(tb, typeContactShow, typeNameList.get(groupPosition), model, groupPosition);
            }
            return false;
        }
        
    };
    
    
    
    public void showTypeLongDialog(final TypeBean tb, String[] typeContactShow, String dialogName, final int model, final int position){
        new AlertDialog.Builder(this).setTitle(dialogName).setItems(typeContactShow,
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                switch(which){
                //"发送短信"
                case 0:
                    List<MyContact> contactList = typeContactData.get(position);
                    String contactsIds = "";
                    for(MyContact mc : contactList){
                        contactsIds += mc.getContactsId() + ",";
                    }
                    if(TextUtils.isEmpty(contactsIds)){
                        return;
                    }
                    contactsIds = contactsIds.substring(0, contactsIds.length() -1);
                    Intent typeSmsIntent = new Intent();
                    typeSmsIntent.putExtra("contactsIds", contactsIds);
                    typeSmsIntent.setClass(TypeContactActivity.this, TypeSmsActivity.class);
                    startActivityForResult(typeSmsIntent, MUTIL_SMS_REQUEST_CODE);
                    break;
                    
                //"添加任务"
                case 1:
                    Intent intentAdd = new Intent();
                    Calendar c = Calendar.getInstance();
                    int year = c.get(Calendar.YEAR);
                    int month = c.get(Calendar.MONTH) + 1;
                    int day = c.get(Calendar.DAY_OF_MONTH);
                    String ch_dayOfWeek = DateUtils.getWeek(c.getTime());
                    ArrayList<String> scheduleDate = new ArrayList<String>();
                    scheduleDate.add(year + "");
                    scheduleDate.add(month + "");
                    scheduleDate.add(day + "");
                    scheduleDate.add(ch_dayOfWeek);
                    intentAdd.putStringArrayListExtra("scheduleDate", scheduleDate);
                    if(model == 0){
                        List<MyContact> mcList = typeContactData.get(position);
                        String contactsIdsStr = "";
                        for(MyContact mc : mcList){
                            contactsIdsStr += mc.getContactsId() + ",";
                        }
                        if(TextUtils.isEmpty(contactsIdsStr)){
                            return;
                        }
                        contactsIdsStr = contactsIdsStr.substring(0, contactsIdsStr.length() - 1);
                        intentAdd.putExtra("objectID", contactsIdsStr);
                        intentAdd.putExtra("objectName", "多人任务");
                        intentAdd.putExtra("scheduleMode", "0");
                    }
                    else if(model == 1 || model==2){
                        intentAdd.putExtra("objectID", String.valueOf(tb.getTypeId()));
                        intentAdd.putExtra("objectName", tb.getTypeName());
                        intentAdd.putExtra("scheduleMode", "1");
                        
                    }
                    else{
                        return;
                    }
                    intentAdd.putExtra("operateType", "add");
                    intentAdd.putExtra("from", "TypeContactActivity");
                    intentAdd.setClass(TypeContactActivity.this, ScheduleView.class);
                    startActivityForResult(intentAdd, TASK_ADD_REQUEST_CODE);
                    break;
                    
                //"编辑分类组员"
                case 2:
                    Intent contactselectIntent = new Intent();
                    contactselectIntent.putExtra("type_id", tbList.get(position - sysOldCount).getTypeId());
                    //1表示分类 2表示群组
                    contactselectIntent.putExtra("work_type", ContactSelectActivity.WORK_TYPE_TYPE);
                    contactselectIntent.putExtra("position", position);
                    contactselectIntent.setClass(TypeContactActivity.this, ContactSelectActivity.class);
                    startActivityForResult(contactselectIntent, EDIT_TYPE_CONTACT_REQUEST_CODE);
                    break;
                    
                //"编辑分类名称"
                case 3:
                    Intent intent = new Intent();
                    intent.putExtra("type_id", tb.getTypeId());
                    intent.putExtra("type_name", tb.getTypeName());
                    intent.putExtra("edit", true);
                    intent.putExtra("position", position);
                    intent.setClass(TypeContactActivity.this, AddEditTypeActivity.class);
                    startActivityForResult(intent, EDIT_REQUEST_CODE);
                    break;
                    
                //"删除分类"
                case 4:
                    deleteNotSysType(tb.getTypeId(), position);
                    break;
                }
            }
        }).show();
    }
    
    //删除非系统的分类
    private void deleteNotSysType(final int typeId, final int position){
        new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher).setTitle("如分类存在人员，会一并清除分类下的人员")
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                SQLiteDatabase dataBase = manager.getWritableDatabase();
                dataBase.delete(DBInitScript.Table_Type_Middle, "typeid=" + typeId, null);
                dataBase.delete(DBInitScript.Table_TypeInfo, "type_id=" + typeId, null);
                typeNameList.remove(position);
                typeContactData.remove(position);
                tbList.remove(position - sysOldCount);
                adapter.notifyDataSetChanged();
                Toast.makeText(TypeContactActivity.this, "该联系人已经被删除.", Toast.LENGTH_SHORT).show();
            }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        }).show();
        
        
        
        
        
    }
    
    
    public static String[] SMS_COLUMNS = new String[]{  
        "thread_id"
    };
    
    private String getSMSThreadId(String adddress){
        Cursor cursor = null;  
        ContentResolver contentResolver = getContentResolver();  
        cursor = contentResolver.query(Uri.parse("content://sms"), SMS_COLUMNS, " address like '%" + adddress + "%' ", null, null);  
        String threadId = "";
        if (cursor == null || cursor.getCount() > 0){
            cursor.moveToFirst();
            threadId = cursor.getString(0);
            cursor.close();
            return threadId;
        }else{
            cursor.close();
            return threadId;
        }
    }
    
    private void attentContact(MyContact cb){
        SQLiteDatabase database = manager.getWritableDatabase();
        ContentValues values = new ContentValues();
        if(cb.getIsAttention() == 1){
            values.put("is_attention", 0);
        }
        else{
            values.put("is_attention", 1);
        }
        int result = database.update(DBInitScript.Table_ContactsInfo, values, "sys_contactid=?", new String[]{cb.getSysContactId() + ""});
        if(result == -1){
            Toast.makeText(getApplicationContext(), "操作失败", Toast.LENGTH_LONG).show();
        }
        if(cb.getIsAttention() == 1){
            Toast.makeText(getApplicationContext(), "取消关注", Toast.LENGTH_LONG).show();
            cb.setIsAttention(0);
        }
        else {
            Toast.makeText(getApplicationContext(), "关注成功", Toast.LENGTH_LONG).show();
            cb.setIsAttention(1);
        }
        database.close();
    
    }
  //群组联系人弹出页
    private void showContactDialog(final String[] arg ,final MyContact cb, final TypeBean tb, final int goupPosition,  final int position){
        new AlertDialog.Builder(this).setTitle(cb.getName()).setItems(arg,
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){

                Uri uri = null;

                switch(which){

                case 0://打电话
                    String toPhone = cb.getMobilePhone();
                    uri = Uri.parse("tel:" + toPhone);
                    Intent it = new Intent(Intent.ACTION_CALL, uri);
                    startActivity(it);
                    break;

                case 1://发短息
                    String phoneNum = cb.getMobilePhone();
                    String threadId = getSMSThreadId(phoneNum);
                    if(TextUtils.isEmpty(phoneNum)){
                        Toast.makeText(getApplicationContext(), "手机号码为空", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("phoneNumber", phoneNum);
                    map.put("threadId", threadId);
                    BaseIntentUtil.intentSysDefault(TypeContactActivity.this, MessageBoxList.class, map);
                    break;

                case 2:// 查看详细       修改联系人资料
                    Intent intent2 = new Intent();
                    SQLiteDatabase sqlAction = manager.getWritableDatabase();
                    Cursor cursor = sqlAction.query(DBInitScript.Table_ContactsInfo, null, "sys_contactid=" + cb.getSysContactId(), null, null, null, null, null);
                    if(cursor == null || cursor.getCount() != 1){
                        break;
                    }
                    //设置为编辑操作
                    intent2.putExtra("edit", true);
                    cursor.moveToFirst();
                    int index = -1;
                    index = cursor.getColumnIndex("contacts_id");
                    intent2.putExtra("contacts_id", cursor.getInt(index));
                    
                    index = cursor.getColumnIndex("sys_contactid");
                    intent2.putExtra("sys_contactid", cursor.getInt(index));
                    
                    index = cursor.getColumnIndex("name");
                    intent2.putExtra("name", cursor.getString(index));
                    
//                    index = cursor.getColumnIndex("age");
//                    intent2.putExtra("age", cursor.getInt(index));
                    
                    index = cursor.getColumnIndex("job");
                    intent2.putExtra("job", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("address");
                    intent2.putExtra("address", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("email");
                    intent2.putExtra("email", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("sex");
                    intent2.putExtra("sex", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("favious");
                    intent2.putExtra("favious", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("company");
                    intent2.putExtra("company", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("remarks");
                    intent2.putExtra("remarks", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("family_phone");
                    intent2.putExtra("family_phone", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("office_phone");
                    intent2.putExtra("office_phone", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("mobile_phone");
                    intent2.putExtra("mobile_phone", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("birth_date");
                    intent2.putExtra("birth_date", cursor.getString(index));
                    
                    intent2.setClass(TypeContactActivity.this, AddNewActivity.class);
                    startActivityForResult(intent2, HomeContactActivity.CONTACT_ADD_EDIT_REQUST_CODE);
                    cursor.close();
                    sqlAction.close();
                    break;

                case 3:// 关注
                    attentContact(cb);
                    break;
                case 4://添加任务
                    Intent intentAdd = new Intent();
                    Calendar c = Calendar.getInstance();
                    int year = c.get(Calendar.YEAR);
                    int month = c.get(Calendar.MONTH) + 1;
                    int day = c.get(Calendar.DAY_OF_MONTH);
                    String ch_dayOfWeek = DateUtils.getWeek(c.getTime());
                    ArrayList<String> scheduleDate = new ArrayList<String>();
                    scheduleDate.add(year + "");
                    scheduleDate.add(month + "");
                    scheduleDate.add(day + "");
                    scheduleDate.add(ch_dayOfWeek);
                    intentAdd.putStringArrayListExtra("scheduleDate", scheduleDate);
                    SQLiteDatabase sqlAction2 = manager.getWritableDatabase();
                    Cursor cursor2 = sqlAction2.query(DBInitScript.Table_ContactsInfo, null, "sys_contactid=" + cb.getSysContactId(), null, null, null, null, null);
                    if(cursor2 == null || cursor2.getCount() != 1){
                        break;
                    }
                    cursor2.moveToFirst();
                    int indexAdd = cursor2.getColumnIndex("contacts_id");
                    intentAdd.putExtra("objectID", String.valueOf(cursor2.getInt(indexAdd)));
                    indexAdd = cursor2.getColumnIndex("name");
                    intentAdd.putExtra("objectName", cursor2.getString(indexAdd));
                    intentAdd.putExtra("operateType", "add");
                    intentAdd.putExtra("from", "TypeContactActivity");
                    intentAdd.setClass(TypeContactActivity.this, ScheduleView.class);
//                  startActivityForResult(intentAdd,0);
                    //代表单人或者多人任务
                    intentAdd.putExtra("scheduleMode", "0");
                    startActivityForResult(intentAdd, HomeContactActivity.TASK_ADD_REQUEST_CODE);
                    cursor2.close();
                    sqlAction2.close();
                    break;
                case 5:// 删除
                    showDelete(cb.getContactsId(), tb.getTypeId(), goupPosition,  position);
                    break;
                }
            }
        }).show();
    }
    
 // 删除联系人方法
    private void showDelete(final int contactsID, final int typeId, final int groupPosition, final int position) {
        new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher).setTitle("是否删除此分类的联系人")
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                SQLiteDatabase dataBase = manager.getWritableDatabase();
                dataBase.delete(DBInitScript.Table_Type_Middle, "contactsid=" + contactsID + " and typeid=" + typeId, null);
                adapter.removeChild(groupPosition, position);
                adapter.notifyDataSetChanged();
                Toast.makeText(TypeContactActivity.this, "该联系人已经被删除.", Toast.LENGTH_SHORT).show();
            }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        }).show();
    }

    
    
    private void init(){
        tbList.clear();
        mcList.clear();
        tmbList.clear();
        typeNameList.clear();
        typeContactData.clear();
        sysOldCount = 0;
        sysConfigCount = 0;
        sysCount = 0;
        
        
        typeNameList.add("20至30岁");
        ++sysOldCount;
        typeNameList.add("30至40岁");
        ++sysOldCount;
        
        
        
        
        SQLiteDatabase database = manager.getWritableDatabase();
//        database.beginTransaction();
        StringBuilder sqlType = new StringBuilder();
        sqlType.append("select type_id, type_name, sys_config");
        sqlType.append(" from " + DBInitScript.Table_TypeInfo);
        Cursor cusorType = database.rawQuery(sqlType.toString(), null);
        int typeCount = cusorType.getCount();
        for(int x = 0; x < typeCount; x++){
            cusorType.moveToPosition(x);
            TypeBean addTb = new TypeBean();
            addTb.setTypeId(cusorType.getInt(0));
            addTb.setTypeName(cusorType.getString(1));
            addTb.setSysConfig(cusorType.getInt(2));
            if(addTb.getSysConfig() == 1){
                ++sysConfigCount;
            }
            tbList.add(addTb);
        }
        sysCount = sysOldCount + sysConfigCount;
        StringBuilder sqlMid = new StringBuilder();
        sqlMid.append("select tc_id, typeid, contactsid");
        sqlMid.append(" from " + DBInitScript.Table_Type_Middle);
        Cursor corsurMid = database.rawQuery(sqlMid.toString(), null);
        int midCount = corsurMid.getCount();
        for(int y = 0; y < midCount; y++){
            corsurMid.moveToPosition(y);
            TypeMiddleBean addTmb = new TypeMiddleBean();
            addTmb.setTcId(corsurMid.getInt(0));
            addTmb.setTypeId(corsurMid.getInt(1));
            addTmb.setContactsId(corsurMid.getInt(2));
            tmbList.add(addTmb);
        }
        
        StringBuilder sqlContact = new StringBuilder();
        sqlContact.append("select contacts_id, name, birth_date, sex, company, is_attention, sys_contactid, mobile_phone");
        sqlContact.append(" from " + DBInitScript.Table_ContactsInfo);
        Cursor cursorContact = database.rawQuery(sqlContact.toString(), null);
        int count = cursorContact.getCount();
        if(count <= 0){
            return;
        }
        Calendar bc = Calendar.getInstance();
        int thisYear = bc.get(Calendar.YEAR);
       
        Calendar bc20 = Calendar.getInstance();
        bc20.set(Calendar.YEAR, thisYear - 20);
        Calendar bc30 = Calendar.getInstance();
        bc30.set(Calendar.YEAR, thisYear - 30);
        Calendar bc40 = Calendar.getInstance();
        bc40.set(Calendar.YEAR, thisYear - 40);
        
        List<MyContact> old20_30List = new ArrayList<MyContact>();
        List<MyContact> old30_40List = new ArrayList<MyContact>();
        for(int i = 0; i < count; i++){
            cursorContact.moveToPosition(i);
            int contactsId = cursorContact.getInt(0);
            String name = cursorContact.getString(1);
            String birthDateString = cursorContact.getString(2);
            String sex = cursorContact.getString(3);
            String company = cursorContact.getString(4);
            int isAttention = cursorContact.getInt(5);
            int sysContactId = cursorContact.getInt(6);
            String mobilePhone = cursorContact.getString(7);
            MyContact contact = new MyContact();
            contact.setContactsId(contactsId);
            contact.setName(name);
            contact.setBirthDate(birthDateString);
            contact.setSex(sex);
            contact.setCompany(company);
            contact.setIsAttention(isAttention);
            contact.setSysContactId(sysContactId);
            contact.setMobilePhone(mobilePhone);
            mcList.add(contact);
            if(!TextUtils.isEmpty(birthDateString)){
                    String year = birthDateString.substring(0, 4);
                    String month = birthDateString.substring(4, 6);
                    String day = birthDateString.substring(6, 8);
                    bc.set(Calendar.YEAR, Integer.valueOf(year));
                    bc.set(Calendar.MONTH, Integer.valueOf(month) - 1);
                    bc.set(Calendar.DAY_OF_YEAR, Integer.valueOf(day));
                    if(bc.before(bc20) && bc.after(bc30)){
                        old20_30List.add(contact);
                    }
                    if(bc.before(bc30) && bc.after(bc40)){
                        old30_40List.add(contact);
                    }
            }
        }
        typeContactData.add(old20_30List);
        typeContactData.add(old30_40List);
        
        
       
        
        
        for(TypeBean tb : tbList){
            List<MyContact> newContact = new ArrayList<MyContact>();
            int typeId = tb.getTypeId();
            String typeName = tb.getTypeName();
            typeNameList.add(typeName);
            for(TypeMiddleBean tmb : tmbList){
                int tmbTypeId = tmb.getTypeId();
                int tmbContactsId = tmb.getContactsId();
                if(typeId == tmbTypeId){
                    for(MyContact mc : mcList){
                        int contactsId = mc.getContactsId();
                        if(contactsId == tmbContactsId){
                            newContact.add(mc);
                            break;
                        }
                    } 
                }
                    
            }
            typeContactData.add(newContact);
        }
        cusorType.close();
        cursorContact.close();
//        database.setTransactionSuccessful();
//        database.endTransaction();
        database.close();
    }
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// 先判断是否是返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			manager.close();
		}
		return super.onKeyDown(keyCode, event);
	}
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == EDIT_TYPE_CONTACT_REQUEST_CODE){
            Bundle bd = data.getExtras();
            int typeId = bd.getInt("type_id");
            int position = bd.getInt("position");
            SQLiteDatabase database = manager.getWritableDatabase();
            Cursor cursor = null;
            StringBuilder sqlStr = new StringBuilder();
            sqlStr.append("select contacts_id, name, birth_date, sex, company, is_attention, sys_contactid");
            sqlStr.append(" from " + DBInitScript.Table_ContactsInfo + " c");
            sqlStr.append(" where exists(select 1 from " + DBInitScript.Table_Type_Middle + " tm where c.contacts_id = tm.contactsid and tm.typeid=?)");
            cursor = database.rawQuery(sqlStr.toString(), new String[]{typeId + ""});
            int count = cursor.getCount();
            if(count <= 0){
                typeContactData.get(position).clear();
            }else{
                List<MyContact> mcList = new ArrayList<MyContact>();
                for(int i = 0; i < count; i++){
                    cursor.moveToPosition(i);
                    int contactsId = cursor.getInt(0);
                    String name = cursor.getString(1);
                    String birthDate = cursor.getString(2);
                    String sex = cursor.getString(3);
                    String company = cursor.getString(4);
                    int isAttention = cursor.getInt(5);
                    int sysContactId = cursor.getInt(6);
                    MyContact contact = new MyContact();
                    contact.setContactsId(contactsId);
                    contact.setName(name);
                    contact.setBirthDate(birthDate);
                    contact.setSex(sex);
                    contact.setCompany(company);
                    contact.setIsAttention(isAttention);
                    contact.setSysContactId(sysContactId);
                    mcList.add(contact);
                }
                typeContactData.get(position).clear();
                typeContactData.get(position).addAll(mcList);
            }
            adapter.notifyDataSetChanged();
            cursor.close();
            database.close();
            
            
        }
        else if(requestCode == MUTIL_SMS_REQUEST_CODE){
            
        }
        else if(requestCode == ADD_REQUEST_CODE){
            if(resultCode != 3 && resultCode != 4){
                return;
            }
            Bundle bd = data.getExtras();
            int typeId = bd.getInt("type_id");
            String typeName = bd.getString("type_name");
            TypeBean tb = new TypeBean();
            tb.setTypeId(typeId);
            tb.setSysConfig(0);
            tb.setTypeName(typeName);
            tbList.add(tb);
            typeNameList.add(tb.getTypeName());
            List<MyContact> list = new ArrayList<MyContact>();
            typeContactData.add(list);
            adapter.notifyDataSetChanged();
            
        }
        else if(requestCode == EDIT_REQUEST_CODE){
            if(resultCode != 3 && resultCode != 4){
                return;
            }
            Bundle bd = data.getExtras();
            String typeId = bd.getString("type_id");
            String typeName = bd.getString("type_name");
            int position = bd.getInt("position");
            for(TypeBean tb : tbList){
                if(tb.getTypeId() == Integer.valueOf(typeId)){
                    tb.setTypeName(typeName);
                    break;
                }
            }
            typeNameList.set(position, typeName);
            adapter.notifyDataSetChanged();
        }
        else if(requestCode == HomeContactActivity.CONTACT_ADD_EDIT_REQUST_CODE){
            if(resultCode != 3 && resultCode != 4){
                return;
            }
            init();
            adapter.notifyDataSetChanged();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    @Override
    protected void onDestroy() {
        if(manager != null){
            manager.close();
        }
        super.onDestroy();
    }
    
    
    
}
